package com.msh.automatic.android.control.script.service

import android.accessibilityservice.AccessibilityService
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import com.alibaba.fastjson2.JSON
import com.msh.automatic.android.control.script.task.TaskManager

class ScriptAccessibilityService : AccessibilityService() {

    var currentPackage = ""
    var currentActivity = ""
    val TAG = "ScriptAccessibilityService"

    companion object {
        lateinit var scriptAccessibilityService: ScriptAccessibilityService
    }

    override fun onServiceConnected() {
        super.onServiceConnected()
        // 可选初始化逻辑
        Log.d(TAG, "服务已连接")
//        CoroutineScope(Dispatchers.IO).launch {
//            TaskUtil.callBackService(null,"",this@ScriptAccessibilityService)
//        }
        scriptAccessibilityService = this
        TaskManager.start()
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        Log.d(TAG, "onAccessibilityEvent: ${event.eventType} ${event.action} ${event.contentChangeTypes} ${event.contentDescription} ${JSON.toJSONString(event.text)} ")

        if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && event.contentChangeTypes == AccessibilityEvent.CONTENT_CHANGE_TYPE_UNDEFINED) {
            var packageName = event.packageName?.toString()!!
            var className = event.className?.toString()!!
            // 排除系统视图类名
            if (!className.contains(".") || className.startsWith("android.")) {
                return
            }
            if(packageName != this.rootInActiveWindow.packageName){
                return
            }
            currentPackage = packageName
            currentActivity = className

            Log.d(TAG, "当前Activity: $currentPackage / $currentActivity")
        }
    }

    override fun onInterrupt() {
        Log.d(TAG, "服务中断")
    }

    private fun releaseWakeLock() {

    }
}
